home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_12_06 / gotwals / divrem.cpp < prev    next >
C/C++ Source or Header  |  1994-04-01  |  2KB  |  62 lines

  1. ====================== Listing 6 ======================
  2. int divrem(int *u, int v, int m); // divrem prototype
  3.  
  4. char* LargeInt::binToDec(char* dest, int lim) const {
  5.    LargeInt copy = *this;   // convert this copy
  6.    int* copyAdr = copy.adr; // this will be changed
  7.    int copyLen  = copy.len; // this will be changed
  8.    int binDec; // holds one 10^PackFactor binary digit
  9.    char* initDest = dest;
  10.    int blkCnt, i, j;
  11.  
  12.    // special case of 0
  13.    if (sign == 0) {
  14.       strcpy(dest, "0");
  15.       return initDest;
  16.    }
  17.    // convert to string in blocks of PackFactor
  18.    blkCnt = 0;
  19.    while (*copyAdr != 0  ||  copyLen > 1) {
  20.       binDec = divrem(copyAdr, intTenTo9, copyLen);
  21.       if (copyLen > 1  &&  *copyAdr == 0) {
  22.          copyAdr++;
  23.          copyLen--;
  24.       }
  25.       if (lim - (PackFactor + 1) > 0) { // 1 for '\0'
  26.          sprintf(dest, "%09u", binDec);
  27.          lim  -= PackFactor;
  28.          dest += PackFactor;
  29.       }
  30.       else
  31.          return 0; // short of room for output string
  32.       blkCnt++;
  33.    } // on exit, dest points at null byte
  34.    lim--; // account for the null byte
  35.  
  36.    // swap output in blkCnt groups of size PackFactor
  37.    i = 0; // subscript of beginning of 1st block
  38.    j = (blkCnt - 1) * PackFactor; // last block
  39.    blkCnt &= -2; // only need an even number of swaps
  40.    while (blkCnt > 1) {
  41.       swap9(initDest + i, initDest + j);
  42.       blkCnt -= 2;
  43.       i += PackFactor;
  44.       j -= PackFactor;
  45.    }
  46. //
  47. // Code to remove leading zeros and possibly insert
  48. // minus sign belongs here
  49. //
  50.    return initDest;
  51. }
  52.  
  53. inline void swap9(char* s1, char* s2) {
  54.    char hold;
  55.  
  56.    for (int i = 0; i < PackFactor; i++) {
  57.       hold  = s1[i];
  58.       s1[i] = s2[i];
  59.       s2[i] = hold;
  60.    }
  61. }
  62.